#coding=utf-8
import os
import string
import random
import datetime
from django.conf import settings

def randomize(length=16, charset=string.ascii_letters + string.digits):
    random.seed = (os.urandom(1024))
    return ''.join(random.choice(charset) for i in range(length))

def format_date(date, orig_format, res_format):
    return datetime.datetime.strptime(date, orig_format).strftime(res_format)

def upload_file(f, directory):
    ext = str(f).split(".")[-1]
    filename = "%s.%s" % (randomize(length=8), ext)
    filepath = '%s/%s' % (directory, filename)
    if not os.path.exists(directory):
        os.makedirs(directory)
    with open(filepath, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    return filename

periodDef = datetime.date.today().month
yearDef = datetime.date.today().year

ACCOUNT_STATUS_CHOICES = (
     ('0','待审核'),
     ('1','正常用户'),
     ('2','审核未通过'),
     ('3','锁定用户'),
     ('4','黑名单用户'),
)

USER_MANAGE_OPERATE_CHOICES = (
     ('0','用户管理'),
     ('1','密码重置'),
)

COURSE_TYPE_CHOICES = (
     ('0','科技'),
     ('1','艺术'),
     ('2','体育'),
     ('3','科学'),
     ('4','传统艺术'),
     ('5','社会实践'),
     ('6','其他'),
)

COURSE_STATUS_CHOICES = (
     ('-1','删除'),
     ('0','编辑'),
     ('1','待审核'),
     ('2','退回'),
     ('3','审核通过'),
     ('4','发布'),
     ('9','编辑'),
)

DATA_STATUS_CHOICES = (
     ('0','删除'),
     ('1','正常'),
)

SEX_TYPE_CHOICES = (
     ('0','女'),
     ('1','男'),
)


STUDENT_CHOICE_MESSAGE = (
     ('0','导入'),
)


MODULES_POWER_STATUS_CHOICES = (
     ('0','新入网客户'),
     ('1','正常用电客户'),
     ('2','欠缴正常用电客户'),
     ('3','欠缴停电用户'),
     ('4','黑名单用户'),
     ('5','合同执行完成用户'),
     ('10','追踪用户'),
)

SUB_ITEM_STATUS_CHOICES = (
     ('0','否'),
     ('1','是'),
)

CASE_BATCH_STATUS_CHOICES = (
     ('0','未导入'),
     ('1','正常'),
     ('2','未退案件'),
     ('3','已退案件'),
)
CASE_TYPE_CHOICES = (
     ('0','短期帐'),
     ('1','中期帐'),
)

CASE_CLIENT_CHOICES = (
     ('0','中信银行'),
     ('1','中国工商'),
     ('2','交通银行'),
     ('3','平安银行'),
     ('4','河北银行'),
)

CASE_STATUS_CHOICES = (
     ('0','正常'),
     ('1','暂停'),
     ('2','关档'),
     ('3','退档'),
)

COLLECT_STATUS_CHOICES = (
     ('0','正常'),
     ('1','暂停催收'),
     ('2','无法联系'),
     ('3','查账'),
     ('4','拒绝还款'),
     ('5','退案'),
     ('6','伪冒'),
     ('7','夜间催收'),
     ('8','信函催收'),
     ('9','分期还款'),
     ('10','紧急案件'),
     ('11','密集跟进'),
)

VISIT_STATUS_CHOICES = (
     ('-1','审核未通过'),
     ('0','待审核'),
     ('1','待排程'),
     ('2','完成'),
)

REPAY_STATUS_CHOICES = (
     ('0','正常'),
)

LETTER_ASSOCIAL_STATUS_CHOICES = (
     ('0','待审核'),
     ('1','待处理'),
     ('2','处理中'),
     ('3','已完成'),
)

TYPE_ASSOCIAL_STATUS_CHOICES = (
     ('0','投诉预警'),
     ('1','户籍查询'),
     ('2','法院协催'),
     ('3','社保查询'),
     ('4','公安协催'),
     ('5','争议咨询'),
     ('6','电信查询'),
     ('7','短信申请'),
)

CP_REPAY_STATUS_CHOICES = (
     ('0','有效'),
     ('1','作废'),
) 
PHONE_TYPE_CHOICES = (
     ('0','家庭电话'),
     ('1','办公电话'),
     ('2','手机'),
     ('3','其他电话'),
)

INFO_STATUS_CHOICES = (
     ('0','有效'),
     ('1','无效'),
     ('2','未知'),
) 
ALLOW_STATUS_CHOICES = (
     ('0','允许'),
     ('1','不允许'),
) 
UNIT_TYPE_CHOICES = (
     ('0','城宫教育'),
     ('1','教育机构'),
     ('2','学校'),
     ('3','教育主管部门'),
)

POLIT_TYPE_CHOICES = (
     ('0','群众'),
     ('1','团员'),
     ('2','党员'),
     ('3','民主人士'),
)

QUALIFTY_TYPE_CHOICES = (
     ('0','高中'),
     ('1','专科'),
     ('2','本科'),
     ('3','硕士'),
     ('4','博士'),
     ('5','其他'),
)

RESUME_STATUS_CHOICES = (
     ('0','删除'),
     ('1','编辑'),
     ('2','待审核'),
     ('3','审核通过'),
     ('4','审核未通过'),
)

COURSE_USER_CHOICES = (
     ('0','已选择'),
     ('1','已提交'),
     ('2','已排程'),
     ('3','删除'),
)

MANAGE_COMMENT_TYPE_CHOICES = (
     ('0','课程管理'),
     ('1','课程状态修改'),
     ('2','课程推荐'),
)

COURSE_CONTENT_STRUCTURE_CHOICES = (
     ('1','准备部分'),
     ('2','基础部分'),
     ('3','结束部分'),
)

TIME_AMPM_CHOICES = (
     ('1','上午'),
     ('2','下午'),
)
TEACH_WEEK_CHOICES = (
     ('1','周一'),
     ('2','周二'),
     ('3','周三'),
     ('4','周四'),
     ('5','周五'),
     ('6','周六'),
     ('7','周日'),
)
COURSE_TERM_CHOICES = (
     ('1','上学期'),
     ('2','下学期'),
)

DEFAULT_COURSE_YEAR = '2016'
DEFAULT_COURSE_TERM = '1'

WER_SCOPE_CHOICES = (
     ('1','未授权code'),
     ('2','获取access_token失败'),
     ('3','拉取用户信息失败'),
     ('4','用户初次使用未登录'),
     ('5','用户已登录'),
)

FIT_AGE_CHOICES = (
    ('0','7-9岁'),
    ('1','9-12周岁'),
    ('2','12-15周岁'),
    ('3','无年龄限制'),
)


SUBSCRIBE_TYPE_CHOICES = (
    ('0','未关注'),
    ('1','已关注'),
)

WEIXIN_USER_TYPE_CHOICES = (
    ('2','普通管理员'),
    ('3','授课教师'),
    ('4','教育机构'),
    ('5','学校教师'),
    ('6','学校管理员'),
    ('7','学生家长'),
)


TEMPLATE_TYPE_CHOICES = (
     ('0','管理制度'),
     ('1','关于我们'),
     ('2','简历模板'),
     ('3','课程模板'),
     ('4','课时模板'),
)

WEB_TYPE_IMG_CHOICES = (
     ('0','首页banner'),
     ('1','课程详情'),
     ('2','课程资源'),
     ('3','关于我们'),
    ('4','logo'),
     ('5','公众号二维码'),
)

ATTACH_TYPE_CHOICES = (
     ('0','学校文件'),
     ('1','选课导入'),
)

COURSE_GRADE_MESSAGE = {"A":u"一年级","B":u"二年级","C":u"三年级",
                        "D":u"四年级","E":u"五年级","F":u"六年级",
                        "G":u"初一","H":u"初二","I":u"初三"}

def num_to_chart(num):
    if not num:
        return ''
    else:
        _MAPPING = (u'零', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九', )
        _decade = (u'十',)
        num_list = list(str(num))
        num_len = len(num_list)
        
        return_list = []
        return_list.append(u'第')
        if num_len==1:
            return_list.append(_MAPPING[int(num)])
        else:
            decade = num_list[0]
            if not decade=='1':
                return_list.append(_MAPPING[int(decade)])
            return_list.append(_decade[0])
            if not (num_list[1]=='0'):
                return_list.append(_MAPPING[int(num_list[0])])
            
        return_list.append(u'节')
        return ''.join(return_list)
            
def period_content_struct(base_list):
    data_return = []
    flag = True
    for content in base_list:
        base_dict = {}
        base_dict["content"] = content.content
        base_dict["id"] = content.id
        if flag:
            flag = False
            base_dict["serial"] = content.serial
        base_dict["teach_way"] = content.teach_way
        base_dict["num"] = content.num
        base_dict["name"] = content.name
        base_dict["time"] = content.time
        base_dict["rowspan"] = str(len(base_list))
        data_return.append(base_dict)
    return data_return
            
def period_content_struct_simple(base_list):
    data_return = []
    flag = True
    for content in base_list:
        base_dict = {}
        base_dict["content"] = content.content
        base_dict["id"] = content.id
        if flag:
            flag = False
            base_dict["serial"] = content.serial
        
        base_dict["name"] = content.name
        base_dict["rowspan"] = str(len(base_list))
        data_return.append(base_dict)
    return data_return

import re
def new_line(matched):
    value = matched.group('value')
    if matched.span()[0]==0:
        return str(value)
    else:
        start = matched.span()[1]
        end = start +1
        #print matched
        return str("<br>"+value)

def test_line():
    s = "1.sdfs2.sdfsdf4.df"
    return re.sub('(?P<value>\d+)', new_line, s)

def sequ_string(param_str):
    def new_line(matched):
        value = matched.group('value')
        if matched.span()[0]==0:
            return str(value)
        else:
            start = matched.span()[1]
            end = start +1
            if param_str[start:end] in ['.','、','．']:
                return str("<br>"+value)
            else:
                return str(value)
    return re.sub('(?P<value>\d+)', new_line, param_str)

def sequ_html_string(param_str):
    param_str_test = param_str
    def new_line(matched):
        value = matched.group('value')
       
        if matched.span()[0]==0:
            return str(value)
        else:
            start = matched.span()[0]
            end = matched.span()[1]
            if (param_str_test[start-1:start] != '>') and (param_str_test[end:end+1] in ['.','、','．']):
                return str("</p><p>"+value)
            else:
                return str(value)
    return re.sub('(?P<value>\d+)', new_line, param_str)

def test_sequ_html():
    a = '<p>一、班长集合整队， 二、师生相互问好 三、检查人数及服装&nbsp; 四、宣布本1、次课的任务和2、 迅速集合 3、认真听讲</p>'
    print sequ_catit_html_string(a)
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
def sequ_catit_html_string(param_str):
    resulr_str = sequ_html_string(param_str)
    print resulr_str
    temp_list = resulr_str.split(u'、')
    if temp_list.__contains__(''):
        temp_list.remove('')
    result_list = []
    _MAPPING = (u'十', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九', )
    up_mess = ""
    for temp in temp_list:
        print temp
        temp = temp.decode('utf-8')
        
        cap = temp[-1:]
        ch = temp[-2:-1]
        
        if (cap in _MAPPING) and (ch !='>'):
            result_list.append(temp[:-1])
            result_list.append("</p><p>")
            result_list.append(temp[-1:])
        else:
            result_list.append(temp)
        result_list.append(u"、")
        up_mess = temp
    if len(result_list)>1:
        result_list.pop()
    return ''.join(result_list)

def mkdir_utils(file_dir):
    isExists=os.path.exists(file_dir)
    if not isExists:
        os.makedirs(file_dir)